package cn.zwx.security.example.security.handler;

import cn.zwx.security.example.common.enums.ResultCodeEnum;
import cn.zwx.security.example.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description 登录失败处理类
 * @author zhangwenxue
 * @createTime 2021/6/23 16:12
 **/
@Component
public class UserLoginFailureHandler implements AuthenticationFailureHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * @description 登录失败返回结果
     * @return void
     * @author zhangwenxue
     * @createTime 2021/6/23 16:12
     **/
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception){
        // 这些对于操作的处理类可以根据不同异常进行不同处理
        if (exception instanceof UsernameNotFoundException){
            logger.info("【登录失败】"+exception.getMessage());
            ResultUtil.responseJson(response, ResultCodeEnum.USER_NAME_IS_NOT_FOUND);
        }
        if (exception instanceof LockedException){
            logger.info("【登录失败】"+exception.getMessage());
            ResultUtil.responseJson(response,ResultCodeEnum.USER_IS_FREEZE);
        }
        if (exception instanceof BadCredentialsException){
            logger.info("【登录失败】"+exception.getMessage());
            ResultUtil.responseJson(response,ResultCodeEnum.INCORRECT_USERNAME_PASSWORD);
        }
        ResultUtil.responseJson(response,ResultCodeEnum.LOGIN_FAILED);
    }
}